/*
 * --------------------------------------------------------------
 * Copyright ©  2015 Hangzhou DtDream Technologies Co.,Ltd.
 * --------------------------------------------------------------
 *      Product: 协同数治
 *  Module Name: design
 * Date Created: 2023/1/31
 *  Description: TODO
 * --------------------------------------------------------------
 * Modification History
 * DATE            NAME            Description
 * --------------------------------------------------------------
 * 2023/1/31       yewj            TODO
 * --------------------------------------------------------------
 */

package com.dtdream.pattern.prototype.deepclone;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

/**
 * TODO
 *
 * @Author: yewj
 **/
public class DeepProtoType implements Serializable, Cloneable {

    String name;

    DeepCloneableTarget target;

    public DeepProtoType() {
        super();
    }

    // 深拷贝 - 方式一 使用clone的方法
    @Override
    protected Object clone() throws CloneNotSupportedException {
        // 这里完成对基本数据类型的克隆
        Object deep = super.clone();
        // 对引用类型单独处理
        DeepProtoType deepProtoType = (DeepProtoType) deep;
        deepProtoType.target = (DeepCloneableTarget) target.clone();

        return deepProtoType;
    }

    // 深拷贝 - 方式二 通过对象的序列化实现（推荐）
    public Object deepClone() {
        // 创建对象
        ByteArrayOutputStream bos = null;
        ObjectOutputStream oos = null;
        ByteArrayInputStream bis = null;
        ObjectInputStream ois = null;

        try {
            // 序列化
            bos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(bos);
            oos.writeObject(this);// 当前对象以对象流的形式输出

            //反序列化
            bis = new ByteArrayInputStream(bos.toByteArray());
            ois = new ObjectInputStream(bis);
            DeepProtoType copy = (DeepProtoType) ois.readObject();

            return copy;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            try {
                bos.close();
                oos.close();
                bis.close();
                ois.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }
}
